package com.customer;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.util.MQConnectionUtils;
import com.rabbitmq.client.AMQP.BasicProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 1、主题模式消费者
 * 2、匹配模式：*:匹配多个词语（如：log.info.error 类似的routingKey的消息也可以收到）;#:匹配一个词语（log.info.error的消息收不到，只能收到log.info类似的routingKey的消息）
 */
public class ConsumerSMSTopic {
    private static final String QUEUE_NAME = "consumer_topic_sms";
    private static final String EXCHANGE_NAME = "topic_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        System.out.println("短信消费者启动");
        // 1.创建新的连接
        Connection connection = MQConnectionUtils.newConnection();
        // 2.创建通道
        Channel channel = connection.createChannel();
        // 3.消费者关联队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        // 4.消费者绑定交换机 参数1 队列 参数2交换机 参数3 routingKey
        //*:匹配多个词语（如：log.info.error 类似的routingKey的消息也可以收到）;#:匹配一个词语（log.info.error的消息收不到，只能收到log.info类似的routingKey的消息）
        //channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "log.*");
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "log.#");

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
                    throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("消费者获取生产者消息:" + msg);
            }
        };
        // 5.消费者监听队列消息
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }

}
